import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

import '../../api/models/expenses_model.dart';
import '../../style/theme/responsive.dart';
import '../../style/tokens/font_sizes.dart';
import '../../style/tokens/radius_tokens.dart';
import '../../style/tokens/spacing_tokens.dart';
import 'consumption_calendar_vm.dart';

class ShiftCalendarPage extends StatefulWidget {
  const ShiftCalendarPage({super.key});

  @override
  State<ShiftCalendarPage> createState() => _ShiftCalendarPageState();
}

class _ShiftCalendarPageState extends State<ShiftCalendarPage> {
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;

  @override
  void initState() {
    super.initState();
    _selectedDay = DateTime.now(); // 默认选中今天

    // 进入页面时锁定竖屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
  }

  @override
  void dispose() {
    // 离开页面时恢复默认（允许横竖屏）
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;

    return ChangeNotifierProvider(
        create: (_) => ConsumptionCalendarViewModel()..fetchSchedules(),
        child:
            Consumer<ConsumptionCalendarViewModel>(builder: (context, vm, _) {
          final events = vm.eventsOf(_selectedDay ?? _focusedDay);
          return Scaffold(
              appBar: AppBar(
                title: Text("消费日历"),
                actions: [
                  IconButton(
                      icon: const Icon(Icons.refresh),
                      tooltip: '刷新',
                      onPressed: () async {
                        vm.refreshSchedules(_focusedDay);
                      })
                ],
              ),
              body: Container(
                // decoration: const BoxDecoration(
                //   image: DecorationImage(
                //     image: AssetImage("assets/home/background.jpg"),
                //     // 你的背景图
                //     fit: BoxFit.cover, // 铺满
                //   ),
                // ),
                child: CustomScrollView(
                  slivers: [
                    // 日历部分
                    SliverToBoxAdapter(
                      child: _buildCalendar(vm),
                    ),

                    // 加一个间距
                    SliverToBoxAdapter(
                      child: SizedBox(height: Responsive.h(SpacingTokens.md)),
                    ),

                    // 详情列表部分
                    if (events.isEmpty)
                      SliverToBoxAdapter(
                        child: Padding(
                          padding: const EdgeInsets.all(SpacingTokens.md),
                          child: Center(
                            child: Text(
                              "当日无消费",
                              style: TextStyle(color: Colors.grey.shade600),
                            ),
                          ),
                        ),
                      )
                    else
                      SliverList(
                        delegate: SliverChildBuilderDelegate(
                          (context, index) {
                            final a = events[index];
                            return Container(
                              margin: EdgeInsets.symmetric(
                                  horizontal: Responsive.w(SpacingTokens.sm),
                                  vertical: Responsive.h(SpacingTokens.base)),
                              padding: const EdgeInsets.all(SpacingTokens.sm),
                              decoration: BoxDecoration(
                                color: shiftColor(a.expensesType),
                                borderRadius:
                                    BorderRadius.circular(RadiusTokens.sm),
                                border: Border.all(color: Colors.black12),
                              ),
                              child: Row(
                                children: [
                                  Expanded(
                                    child: Text(
                                        '${a.expensesName} · ${a.expensesType}'),
                                  ),
                                  Text(
                                    '${a.date.year}-${a.date.month}-${a.date.day}',
                                    style: TextStyle(
                                        fontSize: 12,
                                        color: Colors.grey.shade700),
                                  ),
                                ],
                              ),
                            );
                          },
                          childCount: events.length,
                        ),
                      ),
                  ],
                ),
              ));
        }));
  }

  Widget _buildCalendar(ConsumptionCalendarViewModel vm) {
    return TableCalendar<ExpensesAssignment>(
      locale: Localizations.localeOf(context).toString(),
      firstDay: DateTime.utc(2025, 1, 1),
      lastDay: DateTime.utc(2030, 12, 31),
      focusedDay: _focusedDay,
      selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
      onDaySelected: (selectedDay, focusedDay) {
        setState(() {
          _selectedDay = selectedDay;
          _focusedDay = focusedDay;
        });
      },
      onPageChanged: (focusedDay) {
        setState(() {
          _focusedDay = focusedDay;

          final now = DateTime.now();
          if (focusedDay.year == now.year && focusedDay.month == now.month) {
            _selectedDay = now;
          }
        });

        vm.fetchSchedules(
          startDate: DateTime(focusedDay.year, focusedDay.month, 1),
          endDate: DateTime(focusedDay.year, focusedDay.month + 1, 0),
        );
      },
      eventLoader: vm.eventsOf,
      rowHeight: 74,

      // 自定义头部样式
      headerStyle: HeaderStyle(
        formatButtonVisible: false,
        titleCentered: true,
        titleTextStyle: TextStyle(
          fontSize: Responsive.sp(FontSizes.title),
          fontWeight: FontWeight.bold,
          color: Colors.blueGrey.shade800,
        ),
        leftChevronIcon: Icon(Icons.chevron_left, color: Colors.blue.shade400),
        rightChevronIcon:
            Icon(Icons.chevron_right, color: Colors.blue.shade400),
      ),
      // 自定义日期格子样式
      calendarStyle: CalendarStyle(
        isTodayHighlighted: false,
        markersAutoAligned: false,
        weekendTextStyle: TextStyle(color: Colors.grey.shade400),
      ),
      // 自定义格子
      calendarBuilders: CalendarBuilders(
        markerBuilder: (context, date, events) {
          return const SizedBox.shrink();
        },
        defaultBuilder: (context, day, focusedDay) {
          return Container(
            margin: const EdgeInsets.all(SpacingTokens.tiny),
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(color: Colors.grey.shade200, width: 0.8),
              borderRadius: BorderRadius.circular(RadiusTokens.xs),
            ),
            child: SizedBox.expand(
              child: Padding(
                padding: const EdgeInsets.all(SpacingTokens.base),
                child: _DayCellContent(
                  date: day,
                  events: vm.eventsOf(day),
                ),
              ),
            ),
          );
        },
        todayBuilder: (context, day, focusedDay) {
          return Container(
            margin: const EdgeInsets.all(SpacingTokens.tiny),
            decoration: BoxDecoration(
              color: Colors.teal.shade50,
              border: Border.all(color: Colors.teal.shade100, width: 1.2),
              borderRadius: BorderRadius.circular(RadiusTokens.xs),
            ),
            child: SizedBox.expand(
              child: Padding(
                padding: const EdgeInsets.all(SpacingTokens.base),
                child: _DayCellContent(
                  date: day,
                  events: vm.eventsOf(day),
                ),
              ),
            ),
          );
        },
        selectedBuilder: (context, day, focusedDay) {
          return Container(
            margin: const EdgeInsets.all(SpacingTokens.tiny),
            decoration: BoxDecoration(
              color: Colors.lightBlue.shade50,
              border: Border.all(color: Colors.lightBlue.shade100, width: 1.5),
              borderRadius: BorderRadius.circular(RadiusTokens.xs),
            ),
            child: SizedBox.expand(
              child: Padding(
                padding: const EdgeInsets.all(SpacingTokens.base),
                child: _DayCellContent(
                  date: day,
                  events: vm.eventsOf(day),
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

/// 日期格子内容（顶部日期+矩形人员标签）
class _DayCellContent extends StatelessWidget {
  final DateTime date;
  final List<ExpensesAssignment> events;

  const _DayCellContent({
    required this.date,
    required this.events,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 日期数字
        Text(
          '${date.day}',
          style: TextStyle(
              fontSize: Responsive.sp(FontSizes.caption),
              fontWeight: FontWeight.w600),
        ),
        SizedBox(height: Responsive.h(SpacingTokens.base)),
        // 自动换行的人员标签
        Expanded(
          child: Wrap(
            spacing: SpacingTokens.tiny,
            runSpacing: SpacingTokens.tiny,
            children: events.take(2).map((e) {
              return Container(
                padding: const EdgeInsets.all(SpacingTokens.tiny),
                decoration: BoxDecoration(
                  color: shiftColor(e.expensesType),
                  borderRadius: BorderRadius.circular(RadiusTokens.xs),
                  border: Border.all(color: Colors.black12, width: 0.5),
                ),
                child: Text(
                  e.expensesName,
                  style: TextStyle(
                    fontSize: Responsive.sp(FontSizes.labelSmall),
                    fontWeight: FontWeight.w500,
                    color: shiftTextColor(e.expensesType),
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
              );
            }).toList(),
          ),
        ),
      ],
    );
  }
}

Color shiftColor(String type) {
  switch (type) {
    case 'shopping':
      return Colors.purple.shade50;
    case 'dining':
      return Colors.blue.shade50;
    default:
      return Colors.grey.shade100;
  }
}

Color shiftTextColor(String type) {
  switch (type) {
    case 'shopping':
      return Colors.deepPurple.shade600;
    case 'dining':
      return Colors.blue.shade600;
    default:
      return Colors.grey.shade700;
  }
}
